<template>
  <div style="display: inline-flex">
    <el-card style="width: 300px">
      <template #header>
        <div style="
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
          ">
          <!-- <el-avatar src="/favicon.ico" :size="80"></el-avatar> -->
          <el-upload :show-file-list="false" accept=".jpg, .jpeg, .png, .bmp" :http-request="onSaveAvatar">
            <el-avatar :src="avatarUrl" :size="80" title="单击修改头像" />
          </el-upload>
          <el-text style="margin-top: 5px">{{ userCopy.userName }}</el-text>
        </div>
      </template>
      <p>昵称：{{ userCopy.nickName }}</p>
      <p>邮箱：{{ userCopy.email }}</p>
      <p>电话：{{ userCopy.tel }}</p>
    </el-card>
    <el-tabs v-model="activeName" type="card" style="margin-left: 20px; width: 300px">
      <el-tab-pane label="基本信息" name="basic">
        <el-form ref="userFormRef" :model="userForm" :rules="userRules" label-width="auto">
          <el-form-item label="昵称" prop="nickName">
            <el-input autocomplete="off" v-model="userForm.nickName" />
          </el-form-item>
          <el-form-item label="电话" prop="tel">
            <el-input autocomplete="off" v-model="userForm.tel" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input autocomplete="off" v-model="userForm.email" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSave(userFormRef)"> 保存 </el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="修改密码" name="password">
        <el-form ref="pwdFormRef" :model="pwdForm" :rules="pwdRules" label-width="auto">
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input type="password" autocomplete="off" v-model="pwdForm.oldPassword" />
          </el-form-item>

          <el-form-item label="新密码" prop="newPassword">
            <el-input type="password" autocomplete="off" v-model="pwdForm.newPassword" />
          </el-form-item>
          <el-form-item label="确认密码" prop="repeatPassword">
            <el-input type="password" autocomplete="off" v-model="pwdForm.repeatPassword" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSavePassword(pwdFormRef)"> 修改 </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>


<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus';
import api from '@/apis/api';
import appStorage from '@/stores/storage';
import { MittType, StorageKey } from '@/constant';
import emits from '@/utils/emits';
import { UploadReadFile } from '@/utils/tools';
import baseUrl from '@/apis/baseUrl';
const activeName = ref('basic')
const route = useRoute()
const router = useRouter()

const avatarUrl = ref('')
const userCopy = reactive({
  userName: null,
  nickName: null,
  tel: null,
  email: null,
})

const userFormRef = ref();
const userForm = reactive({
  userName: null,
  nickName: null,
  tel: null,
  email: null,
});
const userRules = ref({
  nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  tel: [{ required: true, pattern: /^(((13|14|15|18|17)\d{9}))$/, message: '电话号码不正确，请检查', trigger: 'blur' }],
  email: [{ required: true, pattern: /^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})$/, message: '邮箱不正确，请检查', trigger: 'blur' }],
});

const pwdFormRef = ref();
const pwdForm = reactive({
  oldPassword: null,
  newPassword: null,
  repeatPassword: null,
});
const pwdRules = ref({
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 3, max: 20, message: '密码长度3~20', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 3, max: 20, message: '密码长度3~20', trigger: 'blur' }
  ],
  repeatPassword: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    { min: 3, max: 20, message: '密码长度3~20', trigger: 'blur' }
  ],
});

onMounted(() => {
  loadInfo()
});
function loadInfo(updateStore = false) {
  let userStore = appStorage.getSession(StorageKey.USER)
  // console.log(userStore)
  api.user.get(userStore.userId, resp => {
    let userInfo = resp.data
    userCopy.userName = userInfo.userName
    userCopy.nickName = userInfo.nickName
    userCopy.tel = userInfo.tel
    userCopy.email = userInfo.email

    userForm.userName = userInfo.userName
    userForm.nickName = userInfo.nickName
    userForm.tel = userInfo.tel
    userForm.email = userInfo.email
    //头像
    avatarUrl.value = `${baseUrl.avatarUrl}/${userInfo.avatar}?t=${new Date().getTime()}`

    if (updateStore) {
      appStorage.setSession(StorageKey.USER, userInfo)
      emits.emit(MittType.UserInfo, userInfo)//通知更新
    }
  })
}
//修改个人信息
async function onSave(formEl) {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      api.user.editInfo(userForm.nickName, userForm.email, userForm.tel, resp => {
        loadInfo(true)//刷新当前页信息          
        ElMessage('修改成功')

      }, null)
    }
  })

}
function onReset() {
  userForm.nickName = userCopy.nickName
  userForm.tel = userCopy.tel
  userForm.email = userCopy.email
}
//修改密码
async function onSavePassword(formEl) {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let flag = true
      if (pwdForm.newPassword != pwdForm.repeatPassword) {
        ElMessage.error('确认密码与新密码不一致')
        flag = false
      }
      if (!flag) return

      api.user.editPassword(pwdForm.oldPassword, pwdForm.newPassword, resp => {
        pwdForm.oldPassword = ''
        pwdForm.newPassword = ''
        pwdForm.repeatPassword = ''
        ElMessage('密码修改成功')
      }, null);
    }
  });
}

//修改头像
async function onSaveAvatar(param) {
  // console.log(param)
  let fileName = param.file.name
  UploadReadFile(param.file, (data) => {
    api.user.editAvatar({ fileName: fileName, base64String: data }, resp => {
      // console.log(resp)
      loadInfo(true)
    }, null)
  }, null)
}
</script>


<style lang="less" scoped></style>